﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Tb.App.ErrorCode;

namespace Tb.App.API.Controllers.Rabbit
{
    /// <summary>
    /// 上传图片控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UpLoadFileController : ControllerBase
    {
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<UpLoadFileController> logger;
        /// <summary>
        /// 注入网络主机环境
        /// </summary>
        private readonly IWebHostEnvironment web;

        public UpLoadFileController(ILogger<UpLoadFileController> logger,IWebHostEnvironment web)
        {
            this.logger = logger;
            this.web = web;
        }
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="file">文件</param>
        /// <returns>返回上传任务</returns>
        [HttpPost]
        public Task<ApiResult<string>> UploadFile(IFormFile file)
        {

            try
            {
                logger.LogInformation("-==上传图片==操作日志-");
                ApiResult<string> result = new ApiResult<string>();
                result.Code=ApiEnum.添加成功;
                result.Message=ApiEnum.添加成功.ToString();

                string path=web.WebRootPath+@"\img\"+"_A_"+file.FileName;
                using(FileStream fs=System.IO.File.Create(path))
                {
                    file.CopyTo(fs);
                    fs.Close();
                }
                var url = Request.Scheme + "://" + Request.Host + "/img/" + "_A_" + file.FileName;
                result.Data = url;

                return Task.FromResult(result);

            }
            catch (Exception ex)
            {
                logger.LogError("=>" + ex.Message);
                
                throw;
            }
        }
    }
}
